#include "db_cfg.h"

#include <pugixml.hpp>

#include <common/log/log.h>

bool DBCfg::init()
{
    pugi::xml_document doc;
    auto result = doc.load_file("db.xml");
    if (!result)
    {
        LOG_ERROR("Parse db.xml failed. " << result.description());
        return false;
    }

    auto dbNode = doc.child("root").child("DBInfos").child("db");
    if (!dbNode)
    {
        LOG_ERROR("DB info not config.");
        return false;
    }

    dbInfo_.addr = dbNode.attribute("addr").as_string();
    dbInfo_.port = dbNode.attribute("port").as_string();
    dbInfo_.user = dbNode.attribute("user").as_string();
    dbInfo_.passwd = dbNode.attribute("passwd").as_string();
    dbInfo_.dbname = dbNode.attribute("dbname").as_string();

    auto schemaNode = dbNode.child("schema");
    if (!schemaNode)
    {
        LOG_ERROR("No create schema sql.");
        return false;
    }
    dbInfo_.sqlSchema = schemaNode.child_value();

    auto versionNode = dbNode.child("versionTable");
    if (!versionNode)
    {
        LOG_ERROR("No create version table sql.");
        return false;
    }
    dbInfo_.sqlVersion = versionNode.child_value();

    auto tablesNode = dbNode.child("tables");
    for ( auto& it : tablesNode)
    {
        std::string tableName = it.attribute("name").as_string();
        int32_t version = it.attribute("version").as_int();
        std::string sql = it.child_value();
        dbInfo_.sqlTables[tableName][version] = sql;
    }

    return true;
}
